# -*- coding:utf-8 -*-
import MySQLdb, json
import os
os.sys.path.append('../../utils/constants/')
from constants import *

class discussDao(object):
    "discuss: let me tell u sth about storage-visiting"
    def __init__(self, mysql_conn):
        self.__nessary_list = [ (type(''), "content"), \
                             (type(''), "title"), \
                             (type(10), "sex"), \
                             (type(1L), "age"), \
                             (type(''), "uip"), \
                             (type(10), "discuss_uid"), \
                             (type(10), "last_reply_time"), \
                             (type(u''), "discuss_uname"), \
                             (type(10), "creat_time"),]
        self.__optional_list = [ (type(''), "selected"), \
                             (type(''), "imgurl"), \
                             (type(10), "itype"),]
        self.__db_discuss_table = 'discuss'
        self.__list_size = 20
        self.__discuss_output_list = ['discuss_id', 'itype', 'sex', 'age', 'discuss_uid', 'discuss_uname', \
                'ding_count', 'comm_count', 'pv_count', 'imgurl', 'last_reply_time', \
                'selected', 'title', 'content',]
        self.__discuss_output_detail = ['discuss_id', 'itype', 'sex', 'age', 'discuss_uid', 'discuss_uname', \
                'ding_count', 'comm_count', 'pv_count', 'imgurl', 'last_reply_time', 'status', \
                'selected', 'title', 'content', ]
        self.__db_conn     = mysql_conn

    def __is_valid(self, discuss_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        if not discuss_item:
            ret['retcode'] = E_VALUE_NONE
            ret['message'] = 'discuss_item is None'
            return ret
        for key_item in self.__nessary_list:
            if not discuss_item.has_key(key_item[1]):
                ret['retcode'] = E_KEY_NOT_EXIST
                ret['message'] = 'field[%s] not exist' % (key_item[1], )
                return ret
            if type(discuss_item[key_item[1]]) != key_item[0]:
                ret['retcode'] = E_VALUE_TYPE_ERROR
                ret['message'] = 'field[%s] type error. wish[%s]' % (key_item[1], key_item[0],)
                #print key_item[1], type(discuss_item[key_item[1]]), discuss_item[key_item[1]]
                return ret
            if None == discuss_item[key_item[1]]:
                ret['retcode'] = E_VALUE_IS_EMPTY
                ret['message'] = 'field[%s] empty value' % (key_item[1], )
                return ret
        return ret

    def remove(self, delete_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"

        key_list = ['discuss_id', 'status',]
        for key in key_list:
            if not delete_item.has_key(key):
                ret['retcode'] = E_KEY_NOT_EXIST
                ret['message'] = "delete_item field [%s] not exist" % (key, )
                return ret
        strSQL = 'UPDATE %s SET status = %u WHERE discuss_id = %u;' % \
                (self.__db_discuss_table, delete_item['status'], delete_item['discuss_id'], )
        
        #print strSQL
        self.__db_conn.execute(strSQL)
        return ret
    def add(self, discuss_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        check_ret = self.__is_valid(discuss_item)
        if 0 != check_ret['retcode']:
            return check_ret
        discuss4insert = {}
        for key in self.__nessary_list:
            discuss4insert[key[1]] = discuss_item[key[1]]
        # 把tags变成一个字符串
        #if discuss_item.has_key('tags') and type(discuss_item['tags']) == type([]):
        #    discuss4insert['tags'] = '_'.join(discuss_item['tags'])
        #else:
        #    discuss4insert['tags'] = ''

        field_list = self.__nessary_list + self.__optional_list
        field_key_list = ''
        field_value_list = ''
        conn = self.__db_conn._db
        for  field in field_list:
            if not discuss_item.has_key(field[1]):
                continue
            field_key_list += '%s, ' % (field[1],)
            if field[0] == type(10):
                field_value_list += '%u, ' % (discuss_item[field[1]],)
            elif field[0] == type(1L):
                field_value_list += '%u, ' % (discuss_item[field[1]],)
            elif field[0] == type(''):
                field_value_list += '"%s", ' % (conn.escape_string(discuss_item[field[1]].replace('%', '％')),)
            elif field[0] == type(u''):
                field_value_list += '"%s", ' % (conn.escape_string(discuss_item[field[1]]),)
            else:
                assert 0
        field_key_list = field_key_list[:-2] + ' '
        field_value_list = field_value_list[:-2] + ' '

        strSQL = 'INSERT INTO %s (%s) VALUES (%s);' % (self.__db_discuss_table, field_key_list, field_value_list,)
        # -1- 插入discuss表
        #print strSQL
        self.__db_conn.execute(strSQL)
        return ret

    def mod(self, discuss_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        if not discuss_item.has_key('discuss_id') :
            ret['retcode'] = E_KEY_NOT_EXIST
            ret['message'] = "discuss_item field [%s] not exist" % ('discuss_id', )
            return ret
        discuss_id = discuss_item['discuss_id']
        # 把tags变成一个字符串
        #if discuss_item.has_key('tags') and type(discuss_item['tags']) == type([]):
        #    discuss_item['tags'] = '_'.join(discuss_item['tags'])
        #else:
        #    discuss_item['tags'] = ''

        conn = self.__db_conn._db
        field_list = self.__optional_list
        key_value_list = ''
        for  field in field_list:
            if not discuss_item.has_key(field[1]):
                continue
            key_value_list += '%s=' % (field[1],)
            if field[0] == type(10):
                key_value_list += '%u, ' % (discuss_item[field[1]],)
            elif field[0] == type(''):
                key_value_list += '"%s", ' % (conn.escape_string(discuss_item[field[1]].replace('%', '％')),)
            else:
                assert 0
        key_value_list = key_value_list[:-2] + ' '

        strSQL = 'UPDATE %s SET %s WHERE discuss_id = %u;' % (self.__db_discuss_table, key_value_list, discuss_id,)
        # -1- 插入discuss表
        #print strSQL
        self.__db_conn.execute(strSQL)
        return ret

    def ding(self, ding_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        # 检查合法性
        if not ding_item.has_key('discuss_id') or not ding_item.has_key('ding'):
            ret['retcode'] = E_KEY_NOT_EXIST
            ret['message'] = "ding_item field [%s] or [%s] not exist" % ('discuss_id', 'ding', )
            return ret
        # -1- 更新discuss的ding计数，锁表控制并发??
        #self.__db_conn.autocommit(False)
        strSQL  = 'SET AUTOCOMMIT = 0;'
        strSQL += ' SELECT ding_count FROM discuss WHERE discuss_id=%u FOR UPDATE;' % (ding_item['discuss_id'],)
        strSQL += ' UPDATE discuss SET ding_count = ding_count+1 WHERE discuss_id=%u;' % (ding_item['discuss_id'],)
        strSQL += ' COMMIT; SET AUTOCOMMIT = 1;'
        #print strSQL
        self.__db_conn.execute(strSQL)
        #self.__db_conn.commit()
        #self.__db_conn.autocommit(True)
        return ret

    def add_pv_count(self, discuss_id):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        # -1- 更新discuss的pv计数，锁表控制并发??
        #self.__db_conn.autocommit(False)
        strSQL  = 'SET AUTOCOMMIT = 0;'
        strSQL += ' SELECT pv_count FROM discuss WHERE discuss_id=%u FOR UPDATE;' % (discuss_id,)
        strSQL += ' UPDATE discuss SET pv_count = pv_count+1 WHERE discuss_id=%u;' %\
                (discuss_id,)
        strSQL += ' COMMIT; SET AUTOCOMMIT = 1;'
        #print strSQL
        self.__db_conn.execute(strSQL)
        #self.__db_conn.commit()
        #self.__db_conn.autocommit(True)
        return ret

    #def query_by_uid(self, uid, pageno):
    #    cursor = self.__db_conn.cursor()

    #    select_list = self.__discuss_output_list
    #    select_key_string = ', '.join(select_list)
    #    strSQL = 'SELECT %s FROM %s WHERE discuss_uid = %u and status = 0  ORDER BY discuss_id DESC limit %u, %u;' %\
    #            (select_key_string, self.__db_discuss_table, uid, pageno*self.__list_size, self.__list_size)
    #    count = cursor.execute(strSQL) 
    #    db_result_list = cursor.fetchmany(count)
    #    output_list = []
    #    for x in db_result_list:
    #        output_item = {}
    #        for step in range(len(select_list)):
    #            if select_list[step] == 'tags':
    #                output_item[select_list[step]] = x[step].split('_')
    #            else:
    #                output_item[select_list[step]] = x[step]
    #            #print select_list[step], '->', x[step]
    #        output_list.append(output_item)
    #    return output_list
    def order_by(self, field, pageno, desc = True):
        select_list = self.__discuss_output_list
        select_key_string = ', '.join(select_list)
        sort_order = desc and "DESC" or "ASC"
        strSQL = 'SELECT %s FROM %s WHERE status = 0 ORDER BY %s %s limit %u, %u;' %\
                (select_key_string, self.__db_discuss_table, field, sort_order, pageno*self.__list_size, self.__list_size)
        output_list = self.__db_conn.query(strSQL)
        if output_list:
            return output_list
        else:
            return []

    def get_discuss(self, discuss_id):
        select_list = self.__discuss_output_detail
        select_key_string = ', '.join(select_list)
        strSQL = 'SELECT %s FROM %s WHERE discuss_id = %u;' %\
                (select_key_string, self.__db_discuss_table, discuss_id,)
        discuss_item = self.__db_conn.get(strSQL)
        if discuss_item:
            return discuss_item
        else:
            return {}
